package io.sdl.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 档案编号生成工具类
 *
 *  @author Dc 1211734836@qq.com
 *  @since 1.0.0 2025-04-22
 *
 */
public final class ArchiveNumberUtil {

    // 私有构造方法防止实例化
    private ArchiveNumberUtil() {}

    // 单例实例
    private static final ArchiveNumberUtil INSTANCE = new ArchiveNumberUtil();

    // 原子序列号，保证线程安全
    private final AtomicInteger sequence = new AtomicInteger(1);

    // 默认配置
    private String orgCode = "SDL001";
    private String archiveType = "SDL";
    private String datePattern = "yyyyMMdd";
    private int sequenceLength = 4;
    private String separator = "-";
    private boolean resetDaily = true;
    private String lastDateStr = "";

    /**
     * 获取工具类实例
     */
    public static ArchiveNumberUtil getInstance() {
        return INSTANCE;
    }

    /**
     * 生成档案编号
     */
    public synchronized String generate() {
        String currentDateStr = getCurrentDateStr();

        // 如果是新的一天且设置了每日重置，则重置序列号
        if (resetDaily && !currentDateStr.equals(lastDateStr)) {
            sequence.set(1);
            lastDateStr = currentDateStr;
        }

        int seq = sequence.getAndIncrement();
        String seqStr = String.format("%0" + sequenceLength + "d", seq);

        return String.join(separator,
                orgCode,
                archiveType,
                currentDateStr,
                seqStr);
    }

    /**
     * 获取当前日期字符串
     */
    private String getCurrentDateStr() {
        return new SimpleDateFormat(datePattern).format(new Date());
    }

    /* ---------- 配置方法 ---------- */

    public ArchiveNumberUtil withOrgCode(String orgCode) {
        this.orgCode = orgCode;
        return this;
    }

    public ArchiveNumberUtil withArchiveType(String archiveType) {
        this.archiveType = archiveType;
        return this;
    }

    public ArchiveNumberUtil withDatePattern(String datePattern) {
        this.datePattern = datePattern;
        return this;
    }

    public ArchiveNumberUtil withSequenceLength(int length) {
        this.sequenceLength = length;
        return this;
    }

    public ArchiveNumberUtil withSeparator(String separator) {
        this.separator = separator;
        return this;
    }

    public ArchiveNumberUtil withResetDaily(boolean resetDaily) {
        this.resetDaily = resetDaily;
        return this;
    }

    /**
     * 重置序列号
     */
    public void resetSequence() {
        sequence.set(1);
    }

}